<template>
    <div class="login">
        <div class="main">
            <div class="content">
                <div class="left">
                    <div class="left-bottom">
                        <img src="../../assets/img/login/login.gif" alt="">
                    </div>
                    <div class="left-top">
                        <img src="../../assets/img/login/login_logo.png" alt="">
                    </div>
                </div>
                <div class="right">
                    <div class="rightContent">
                        <div class="title">易控智驾数据管理平台</div>
                        <div class="tabs">
                            <div class="tabs-item" :class="{ 'active': loginWay === item.tab }" v-for="item in tabs"
                                :key="item.tab" @click="tabClick(item.tab)">
                                <span class="name">{{ item.name }}</span>
                                <span class="divide"></span>
                            </div>
                        </div>
                        <div class="formBox">
                            <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="0px"
                                class="demo-ruleForm">
                                <template v-if="loginWay === 1">
                                    <el-form-item label="" prop="username">
                                        <el-input v-model.trim="ruleForm.username" type="text" autocomplete="off"
                                            placeholder="请输入用户名" @keyup.enter="submitForm(ruleFormRef)" />
                                    </el-form-item>
                                    <el-form-item label="" prop="password">
                                        <div class="inputBox">
                                            <el-input v-model.trim="ruleForm.password" :type="inputType" autocomplete="off"
                                                placeholder="请输入密码" @keyup.enter="submitForm(ruleFormRef)">
                                                <i slots="suffix" class="iconfont eyeIcon"
                                                    :class="[inputType === 'text' ? 'icon-biyan1' : 'icon-yincang']"
                                                    @click="changeInputType"></i>
                                            </el-input>
                                        </div>
                                    </el-form-item>
                                    <el-form-item label="" prop="authcode">
                                        <div class="authBox">
                                            <el-input v-model.trim="ruleForm.authcode" type="text" placeholder="请输入验证码"
                                                @keyup.enter="submitForm(ruleFormRef)" />
                                            <img :src="authcodeUrl" alt="" @click="getAuthCodeUrl">
                                        </div>
                                    </el-form-item>
                                </template>
                                <template v-if="loginWay === 2">
                                    <el-form-item label="" prop="phone">
                                        <el-input v-model="ruleForm.phone" placeholder="请输入手机号"
                                            @keyup.enter="submitForm(ruleFormRef)" />
                                    </el-form-item>
                                    <el-form-item label="" prop="authcode">
                                        <div class="authBox">
                                            <el-input v-model="ruleForm.authcode" type="text" placeholder="请输入验证码"
                                                @keyup.enter="submitForm(ruleFormRef)" />
                                            <span v-if="!getAuthIng" class="authBtn"
                                                @click="getPhoneAuthCode(ruleFormRef)">获取验证码</span>
                                            <span v-if="getAuthIng" class="authBtn">{{ seconds }}秒后重发</span>
                                        </div>
                                    </el-form-item>
                                </template>
                                <el-form-item class="btnFormItem">
                                    <div class="loginBtnBox">
                                        <span v-if="errMsg" class="errorMsg">{{ errMsg }}</span>
                                        <span class="loginBtn" @click="submitForm(ruleFormRef)">登 录</span>
                                    </div>
                                </el-form-item>
                            </el-form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="footer">
            <span>@2022 北京易控智驾科技有限公司 版权所有 | 京ICP备 19030649号-2</span>
        </div>
        <el-dialog title="重置密码" v-model="dialogShow" width="30%" :close-on-press-escape="false" class="loginDialog">
            <div class="dialogContainer">
                <div class="tip">检测到您的密码长时间未修改，请重置密码后登录~</div>
                <el-form label-width="80px" :model="resetForm" ref="resetFormRef" size="medium" :rules="resetRules">
                    <el-form-item label="旧密码" prop="password">
                        <el-input v-model.trim="resetForm.password" placeholder="请输入旧密码" type="password"
                            autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPassword">
                        <el-input v-model.trim="resetForm.newPassword" placeholder="请输入新密码" type="password"
                            autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="确认密码" prop="checkPass">
                        <el-input v-model.trim="resetForm.checkPass" placeholder="请输入确认密码" type="password"
                            autocomplete="off" />
                    </el-form-item>
                </el-form>
                <div class="btnBox">
                    <span class="submitBtn" @click="onsubmit(resetFormRef)">提交</span>
                    <span class="resetBtn" @click="resetPassForm(resetFormRef)">重置</span>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';

import { useGlobalStore } from '@/store/modules/global';
import { useUserStore } from '@/store/modules/user';
import { useRouter } from 'vue-router';
import { sendSmsSign, login, checkLogin, updatePassword, getLoginedUserInfo } from '@/api/modules/user';
import { getToken } from '@/utils/cache/cookies';
import { getUser, setJwtToken } from '@/utils/cache/localStorage';
import { getQueryString } from '@/utils/utilFns';
import { ElMessage } from 'element-plus'

let timer = null;
const accessurl = window.location.protocol + "//" + window.location.host;

const globalStore = useGlobalStore();
const userStore = useUserStore();
const router = useRouter();

const loginWay = ref(1);        // 登陆方式 1: 密码登录  2: 短信登录
const ruleFormRef = ref(null);
const resetFormRef = ref(null);
const authcodeUrl = ref('');
const errMsg = ref('');
const seconds = ref(60);
const getAuthIng = ref(false);
const inputType = ref('password');
const userId = ref('');
const dialogShow = ref(false);

const tabs = reactive([
    { name: '密码登录', tab: 1 },
    { name: '短信登录', tab: 2 }
]);

const ruleForm = reactive({
    username: '',
    password: '',
    phone: '',
    authcode: ''
});

const resetForm = reactive({
    password: '',
    newPassword: '',
    checkPass: ''
});

const rules = reactive({
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    authcode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
});

const validatePass = (rule, value, callback) => {
    if (value === "") {
        callback(new Error("请输入新密码"));
    } else if (value === resetForm.password) {
        callback(new Error("新密码和旧密码不能相同!"));
    } else {
        if (resetForm.checkPass !== "") {
            resetForm.value.validateField("checkPass");
        }
        callback();
    }
};
const validatePass2 = (rule, value, callback) => {
    if (value === "") {
        callback(new Error("请再次输入密码"));
    } else if (value !== resetForm.newPassword) {
        callback(new Error("两次输入密码不一致!"));
    } else {
        callback();
    }
};

const resetRules = reactive({
    password: [{ required: true, trigger: "blur", message: "输入旧密码" }],
    newPassword: [{ required: true, validator: validatePass, trigger: "blur" }],
    checkPass: [{ required: true, validator: validatePass2, trigger: "blur" }],
});

onMounted(() => {
    getAuthCodeUrl();
    analysisUserInfo();
});

// 用户信息解析
const analysisUserInfo = () => {
    const token = getToken();
    const userInfo = getUser();
    const { isLogout } = userStore;

    if (isLogout) return;

    if (!userInfo || !token) {
        analysisUrl();
    }
};

// 解析浏览器地址
const analysisUrl = () => {
    const fromUrl = window.document.referrer;
    if (fromUrl.includes('eqfleetcmder')) {
        const token = getQueryString('t') ? getQueryString('t') : '';
        token && getUserInfo(token);
        // 获取火山BI-token
        token && getJwtToken();
    } else {
        const param = {
            accessUrl: accessurl,
        };
        checkLogin(param).then((res) => {
            if (res.data && res.code == "200") {
                userStore.setUser(res.data);
                userStore.setToken(res.data.token);
                router.push('/home');
            }
        });
    }
};

// 获取用户信息
const getUserInfo = (token) => {
    const params = {
        token,
        accessUrl: accessurl
    };

    getLoginedUserInfo(params)
        .then(res => {
            const { code, data } = res;
            if (code === '200') {
                userStore.setUser(data);
                userStore.setToken(data.token);
                router.push('/home');
            } else {
                this.errMsg = '该账号无权限，请联系管理员!';
            }
        })
};

// 获取火山bi-jwtToken
const getJwtToken = () => {
    const params = {
		metadata: {
			clientId: "255777cf64719e288cf9aad5a7e9e7b2",
			clientSecret: "e4ba5ab5dc4fec1ab97394c8d70c3d84",
			expire: 259200
		}
	};

	const url = 'https://console.volcengine.com/bi/datawind/aeolus/api/v3/openapi/jwtToken';
    axios.post(url, params).then((res) => {
        const jwtToken = res?.data?.data?.jwtToken || '';
        setJwtToken(jwtToken);
    });
};

// 获取验证码
const getAuthCodeUrl = () => {
    const { APP_USER_URL } = window.config;
    const url = `${APP_USER_URL}userLogin/securityCode?d=${new Date().getTime()}`;
    authcodeUrl.value = url;
};

// 密码输入框状态修改
const changeInputType = () => {
    inputType.vlaue = inputType.value === 'text' ? 'password' : 'text';
};

// 获取手机验证码
const getPhoneAuthCode = async (formEl) => {
    if (!formEl) return;

    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!', fields)
        } else {
            console.log('error submit!', fields)
        }
    })

    // ruleForm.value.validateField(
    // 	"phone",
    // 	(errorMessage) => {
    // 		if (errorMessage.length) {
    // 			getAuthIng.value = false;
    // 		} else {
    // 			getAuthIng.value = true;
    // 			countDown();
    // 		}
    // 	}
    // );
};

// 倒计时
const countDown = () => {
    let total = 60;
    seconds.value = total;

    timer = setInterval(() => {
        total--;
        seconds.value = total;
        if (seconds.value === 0) {
            clearInterval(timer);
            timer = null;
            getAuthIng.value = false;
        }
    }, 1000);

    sendAuthCode();
};

// 发送验证码
const sendAuthCode = () => {
    const params = {
        phoneNumber: ruleForm.phone
    };

    sendSmsSign(params).then(res => {
        const { code, resultMsg } = res;
        if (code === 'success') {
            ElMessage({
                type: 'success',
                message: resultMsg || '验证码获取成功!'
            })
        } else {
            ElMessage({
                type: 'error',
                message: resultMsg || '验证码获取失败!'
            })
        }
    });
};

// 登录校验
const submitForm = async (formEl) => {
    await formEl.validate((valid, fields) => {
        if (valid) {
            loginAction();
        } else {
            console.log('error submit!', fields)
        }
    });
};

// 登录
const loginAction = () => {
    const { username, password, phone, authcode } = ruleForm;

    let equal = {
        loginType: loginWay.value,
        accessUrl: accessurl,
    };

    if (loginWay.value === 1) {
        equal = {
            ...equal,
            userName: username,
            password: password,
            imgCode: authcode
        }
    }

    if (loginWay.value === 2) {
        equal = {
            ...equal,
            phone,
            smsCode: authcode
        }
    }

    const params = { equal };
    try {
        login(params).then((res) => {
            const { code = '', data, resultMsg = '' } = res;
            if (code === 'success') {
                userStore.setUser(data);
                getJwtToken();
                userStore.setToken(data.token);
                router.push('/home');
            } else if (code === 'PasswordExpiration') {
                // 检测长时间未修改密码
                showDiaLog(resultMsg);
            } else if (code === "IpInconsistent") {
                errMsg.value = "您的账号异地登录，请使用手机验证码登录";
                loginWay.value = "2";
                ruleForm.phone = resultMsg;
            } else {
                ElMessage({
                    type: 'error',
                    message: resultMsg || '登录失败!'
                });
            }
        }).catch((err) => {console.log(err)});
    } catch (error) {
        throw new Error(error);
    }

};

// 展示重置密码弹框
const showDiaLog = (id) => {
    userId.value = id;
    dialogShow.value = true;
};

const onsubmit = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            handleUpdatePassword();
        } else {
            return false
        }
    })
};

// 更新密码
const handleUpdatePassword = () => {
    const params = {
        id: userId.value,
        password: resetForm.password,
        newPassword: resetForm.newPassword,
    };

    updatePassword(params)
        .then((res) => {
            if (res && res.code === "200") {
                dialogShow.value = false;
                getAuthCodeUrl();
                ElMessage({
                    type: 'success',
                    message: "修改成功，请使用新密码登录!"
                });
                errMsg.value = '';
                ruleForm.password = '';
                ruleForm.authcode = '';
            } else {
                ElMessage({
                    type: 'error',
                    message: "更新失败!"
                });
            }
        })
        .catch(() => {
            dialogShow.value = false;
            errMsg.value = null;
            ElMessage({
                type: 'error',
                message: "更新失败!"
            });
        });
};

const resetPassForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields();
};

const tabClick = (value) => {
    ruleForm.authcode = '';
    loginWay.value = value;
};

</script>

<style lang="scss" scoped>
@import "./Login.scss";
</style>

<style lang="scss">
.loginDialog {
    border: 1.5px solid #000000 !important;

    .el-dialog__title {
        color: #fff !important;
    }

    .el-dialog__header {
        background-color: #203254 !important;
        border-bottom: 1px solid #000000 !important;
        margin-right: 0px;
    }

    .el-form-item {
        margin-bottom: 22px;
    }

    .el-dialog__body {
        background-color: #283f67 !important;
    }

    .el-form-item__label {
        color: #fff !important;
    }

    .el-dialog__close {
        color: #fff !important;
    }

    .el-input__wrapper {
        background-color: #1b2944;
        box-shadow: none;
        border-radius: 0px;
    }
}</style>